package cn.hy.batch;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Map;

// 利用StepExecutionListener传递Job参数
// idea 配置 program argument 参数   name = zhansan
@Configuration
@Slf4j
public class JobParamDemo implements StepExecutionListener {

    Map<String, JobParameter> parameterMap;

    @Override
    public void beforeStep(StepExecution stepExecution) {
        parameterMap = stepExecution.getJobParameters().getParameters();
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return null;
    }

    //注入任务对象工厂
   @Resource
    private JobBuilderFactory jobBuilderFactory;

    //任务的执行由Step决定,注入step对象的factory
   @Resource
    private StepBuilderFactory stepBuilderFactory;

    //创建Job对象
    @Bean
    public Job jobDemo3() {
        return jobBuilderFactory.get("jobDemo3")
                .start(step11())
                .build();

    }

    //创建Step对象

    /**
     * Job执行的Step，Job传递的数据在step中使用
     * 如何给step传递数据?
     * 使用监听器，给step传递数据,实现StepExecutionListener
     *
     * @return
     */
    @Bean
    public Step step11() {
        return stepBuilderFactory.get("step11")
                .listener(this)
                .tasklet(new Tasklet() {
                    @Override
                    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                        log.info("------step11 ok");
                        log.info("参数:" + parameterMap);
                        return RepeatStatus.FINISHED;
                    }
                }).build();
    }
}
